<template>
  <view>
    <!-- 使用 uni-ui 提供的搜索组件 -->
    <view class="search-box">
      <uni-search-bar
        cancelButton="none"
        :radius="100"
        placeholder="请搜索想要的商品"
        @input="inputHandler"
      ></uni-search-bar>
    </view>
    <!-- 搜索建议列表 -->
    <view class="sugg-list" v-if="sugguestions.length > 0">
      <view
        class="sugg-item"
        v-for="(item, index) in sugguestions"
        :key="index"
        @click="goToProductDetail(item)"
      >
        <view class="goods-name">{{ item.goods_name }}</view>
        <uni-icons type="arrowright" size="16"></uni-icons>
      </view>
    </view>
    <!-- 搜索历史 -->
    <view class="history-box" v-else>
      <!-- 标题区域 -->
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="17" @click="clearHistory"></uni-icons>
      </view>

      <!-- 历史列表 -->
      <view class="history-list">
        <uni-tag
          type="success"
          v-for="(item, index) in historyList"
          :key="index"
          :text="item"
          @click="goToProductList(item)"
        ></uni-tag>
      </view>
    </view>
  </view>
</template>

<script>
const KEY = "105-keywords";
export default {
  data() {
    return {
      // 1. 关键字
      keyword: "",
      // 2. 延时器
      timerId: null,
      // 3.搜索建议的数据数组
      sugguestions: [],
      // 4. 搜索关键词的历史记录
      historyList: uni.getStorageSync(KEY) || [],
    };
  },
  methods: {
    // 1. 搜索框输入
    inputHandler(e) {
      // 1.1 清除延时器
      clearTimeout(this.timerId);
      // 1.2 设置延时器
      this.timerId = setTimeout(() => {
        this.keyword = e;
        this.getSugguestionList();
      }, 500);
    },
    // 2. 获取搜索关键词联想
    async getSugguestionList() {
      // 2.1 判断: 如果关键字为空则不请求并清空建议数组
      if (!this.keyword) {
        this.sugguestions = [];
        return;
      }

      // 2.2 请求数据
      const { meta, message } = await this.$http.get("/goods/qsearch", {
        query: this.keyword,
      });
      if (meta.status !== 200) return this.$msg();
      // console.log(message);
      this.sugguestions = message;

      // 2.3 更新历史记录
      this.updateSearchHistory();
    },
    // 3. 跳转去商品详情页
    goToProductDetail(goods) {
      // console.log(goods);
      uni.navigateTo({
        url: `/pages_sub1/product-detail/product-detail?pid=${goods.goods_id}`,
      });
    },
    // 4. 更新搜索历史记录
    updateSearchHistory() {
      this.historyList.unshift(this.keyword);
      // 4.1 关键字去重
      const tempArr = [...new Set(this.historyList)];
      // 4.2 限制关键字数量(10)
      if (tempArr.length > 10) {
        tempArr.pop();
      }
      this.historyList = tempArr;

      // 4.3 持久化到本地
      uni.setStorageSync(KEY, this.historyList);
    },
    // 5. 清空历史记录
    clearHistory() {
      // 清空数组
      this.historyList = [];
      // 删除本地
      uni.removeStorageSync(KEY);
    },
    // 6. 去商品列表页
    goToProductList(item) {
      // console.log(item);
      uni.navigateTo({
        url: `/pages_sub1/product-list/product-list?query=${item}`,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
// 使用样式穿透：覆盖 uni-search-bar 组件的 .uni-searchbar 背景色
::v-deep .uni-searchbar {
  background-color: #c00000 !important;
}

.search-box {
  position: sticky;
  top: 0;
  z-index: 999;
}

// 搜索建议列表
.sugg-list {
  padding: 0 10rpx;

  .sugg-item {
    font-size: 24rpx;
    padding: 26rpx 0;
    border-bottom: 1rpx solid #efefef;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .goods-name {
      margin-right: 6rpx;

      // 溢出部分隐藏
      overflow: hidden;

      // 文字不允许换行
      white-space: nowrap;

      // 文字溢出后使用省略号表示
      text-overflow: ellipsis;
    }
  }
}

// 搜索历史
.history-box {
  padding: 0 10rpx;

  .history-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 80rpx;
    font-size: 26rpx;
    border-bottom: 2rpx solid #efefef;
  }

  .history-list {
    display: flex;
    flex-wrap: wrap;

    uni-tag {
      margin-top: 10rpx;
      margin-right: 10rpx;
    }
  }
}
</style>